﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Reflection;
using Infrastructure.Crosscutting.Task;

namespace Infrastructure.Crosscutting.Comm.Service
{
    public class StartupTaskService
    {
        /// <summary>
        /// Excutes this instance.
        /// </summary>
        public static void Excute()
        {
            List<IStartupTask> startupTaskList = new List<IStartupTask>();
            Assembly asm = GetCurrentExecuteAssembly();
            // get path of executing (bin) folder from the current executing assembly
            string codeBase = GetCurrentExecuteAssembly().CodeBase;
            UriBuilder uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);
            string bin = Path.GetDirectoryName(path);
            string[] assemblies = Directory.GetFiles(bin, "*.dll");
            foreach (String file in assemblies)
            {
                try
                {
                    if (File.Exists(file))
                    {
                        if (file.EndsWith("Telerik.Web.Mvc.Contrib.dll")) continue;
                        // load the assembly
                        asm = Assembly.LoadFrom(file);
                        // get all types from the assembly that inherit IStartupTask
                        var query = from t in asm.GetTypes()
                                    where t.IsClass && t.GetInterface(typeof(IStartupTask).FullName) != null
                                    select t;

                        // add types to list of startup tasks
                        foreach (Type type in query)
                        {
                            startupTaskList.Add((IStartupTask)Activator.CreateInstance(type));
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("error message", ex);
                }
            }

            // execute each startup task
            foreach (IStartupTask task in startupTaskList)
            {
                task.Execute();
            }
        }

        /// <summary>
        /// Gets the current execute assembly.
        /// </summary>
        /// <returns></returns>
        private static Assembly GetCurrentExecuteAssembly()
        {
            var res = Assembly.GetExecutingAssembly();
            return res;
        }
    }
}
